﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace AISservice.Common
{
    public class JsonHelper
    {
        public static string formatstr = "yyyy-MM-dd HH:mm:ss";

        public const string departmentName = "公共文件夹";

        static IsoDateTimeConverter timejson = new IsoDateTimeConverter
        {
            DateTimeFormat = formatstr
        };




        /// <summary>
        /// Unicode编码转换为中文，主要用于JS返回的结果码解析
        /// </summary>
        /// <param name="unicodeStr">Unicode字符串</param>
        public static string UnicodeToGB(string unicodeStr)
        {
            try
            {
                MatchCollection mc = Regex.Matches(unicodeStr, "(\\\\u([\\w]{4}))");
                if (mc != null && mc.Count > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (Match m2 in mc)
                    {
                        string v = m2.Value;
                        string word = v.Substring(2);
                        byte[] codes = new byte[2];
                        int code = Convert.ToInt32(word.Substring(0, 2), 16);
                        int code2 = Convert.ToInt32(word.Substring(2), 16);
                        codes[0] = (byte)code2;
                        codes[1] = (byte)code;
                        unicodeStr = unicodeStr.Replace(v, Encoding.Unicode.GetString(codes));
                        //sb.Append(Encoding.Unicode.GetString(codes));
                    }
                    return unicodeStr;
                }
                else
                {
                    return unicodeStr;
                }
            }
            catch (Exception ex)
            {
                Log4Net.Error(new System.Diagnostics.StackTrace().GetFrame(0).ToString(), ex);
                return "";
            }
        }

        /// <summary>
        /// 格林威治时差（毫秒）转换成标准时间
        /// </summary>
        /// <param name="gelinMilliseconds"></param>
        /// <returns></returns>
        public static string GelinMillisecondsToDate(string gelinMilliseconds)
        {
            gelinMilliseconds += "0000";
            DateTime date = DateTime.Parse("1970-01-01 08:00:00").AddTicks(long.Parse(gelinMilliseconds));
            return date.ToString("yyyy-MM-dd HH:mm:ss");
        }

        /// <summary>
        /// 提取字符串
        /// </summary>
        /// <param name="text"></param>
        /// <param name="startStr"></param>
        /// <param name="endStr"></param>
        /// <returns></returns>
        public static string Abstract(string text, string startStr, string endStr)
        {
            if (string.IsNullOrEmpty(text))
                return "";
            string res = string.Empty;
            if (!string.IsNullOrEmpty(startStr))
            {
                if (!text.Contains(startStr))
                {
                    return res;
                }
                else
                {
                    text = text.Substring(text.IndexOf(startStr) + startStr.Length);
                }
            }
            if (!string.IsNullOrEmpty(endStr))
            {
                if (!text.Contains(endStr))
                {
                    return res;
                }
                else
                {
                    res = text.Substring(0, text.IndexOf(endStr));
                }
            }
            else
            {
                res = text;
            }
            return res;
        }

        public static string UnQuotationMarks(string str)
        {
            if (str[0].Equals('"') && str[str.Length - 1].Equals('"'))
                return str.Substring(1, str.Length - 2);
            return str;
        }

        /// <summary>
        /// 对象Json化
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectToJson(object obj)
        {
            if (obj != null && obj != DBNull.Value)
            {
                String json_res = "";
                if (obj is String || obj is Char)
                {
                    json_res = obj.ToString();
                }
                else
                {
                    //DateTime dt = DateTime.UtcNow;
                    //json_res = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
                    json_res = Newtonsoft.Json.JsonConvert.SerializeObject(obj, timejson);

                }
                return json_res;
            }
            return null;
        }
        /// <summary>
        /// Json对象化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T JsonToObject<T>(string json)
        {
            if (!string.IsNullOrEmpty(json))
            {
                try
                {
                    return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);

                }
                catch (Exception ex)
                {
                    Log4Net.Error(string.Format("json转换实体出错;{0}", ex.Message), ex);
                    throw new Exception(string.Format("json转换实体出错;{0}", ex.Message));
                }
            }
            else
                throw new Exception("json转换实体出错,json为null");
        }


        public static List<object> JsonToListObject(string json)
        {
            if (!string.IsNullOrEmpty(json))
            {
                try
                {
                    //var arrdata = Newtonsoft.Json.Linq.JArray.Parse(json);
                    //List<object> obj2 = arrdata.ToObject<List<object>>();
                    //return obj2;

                    List<dynamic> obj2 = new List<dynamic>();
                    foreach (dynamic obj in Newtonsoft.Json.Linq.JArray.Parse(json))
                    {
                        obj2.Add(obj);
                    }
                    return obj2;
                }
                catch (Exception ex)
                {
                    Log4Net.Error(string.Format("json转换实体出错;{0}", ex.Message), ex);
                    throw new Exception(string.Format("json转换实体出错;{0}", ex.Message));
                }
            }
            else
                throw new Exception("json转换实体出错,json为null");
        }

        public static string DataTable2Json(DataTable dt)
        {
            return JsonConvert.SerializeObject(dt, new DataTableConverter());
        }
        public static DataTable Json2DataTable(string str)
        {
            return JsonConvert.DeserializeObject<DataTable>(str, new DataTableConverter());
        }
        public static string CovnertDataToCheckModel(DataTable dt)
        {
            StringBuilder sb = new StringBuilder();
            foreach (DataRow dr in dt.Rows)
            {
                sb.Append("{");
                sb.Append("\"OrderGUID\"" + ":\"" + dr["OrderGUID"].ToString() + "\",");
                sb.Append("\"BasketNo\"" + ":\"" + dr["BasketNo"].ToString() + "\",");
                sb.Append("\"Quantity\"" + ":\"" + dr["Quantity"].ToString() + "\"");
                sb.Append("},");
            }
            sb.Remove(sb.ToString().Length - 1, 1);
            return sb.ToString();
        }

        private static string GetEditBycname(string colname, bool isprimarykey)
        {
            return "true";
        }
        private static string GetDataTypeBycname(string colname, bool isprimarykey)
        {
            if (isprimarykey) return "boolean";
            return "string";
        }
        private static bool GetPrimaryKey(string p1, string colname)
        {
            if (colname == "id") return true; return false;
        }
        private static string GetColUIName(string p1, string colname, bool isprimarykey)
        {
            if (isprimarykey) return "选择";
            return colname.ToUpper();
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }



        /// <summary>
        /// 将字典类型序列化为json字符串
        /// </summary>
        /// <typeparam name="TKey">字典key</typeparam>
        /// <typeparam name="TValue">字典value</typeparam>
        /// <param name="dict">要序列化的字典数据</param>
        /// <returns>json字符串</returns>
        public static string SerializeDictionaryToJsonString<TKey, TValue>(Dictionary<TKey, TValue> dict)
        {
            if (dict.Count == 0)
                return "";

            string jsonStr = JsonConvert.SerializeObject(dict);
            return jsonStr;
        }

        /// <summary>
        /// 将json字符串反序列化为字典类型
        /// </summary>
        /// <typeparam name="TKey">字典key</typeparam>
        /// <typeparam name="TValue">字典value</typeparam>
        /// <param name="jsonStr">json字符串</param>
        /// <returns>字典数据</returns>
        public static Dictionary<TKey, TValue> DeserializeStringToDictionary<TKey, TValue>(string jsonStr)
        {
            if (string.IsNullOrEmpty(jsonStr))
                return new Dictionary<TKey, TValue>();

            Dictionary<TKey, TValue> jsonDict = JsonConvert.DeserializeObject<Dictionary<TKey, TValue>>(jsonStr);

            return jsonDict;

        }

        /// <summary>
        /// Json转Hashtable
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static Hashtable Json2Hashtable(string json)
        {
            Hashtable hashtable = JsonConvert.DeserializeObject<Hashtable>(json);
            return hashtable;

        }


    }

}
